import com.sun.org.apache.bcel.internal.generic.NEWARRAY;

import  java.lang.Math;
import java.sql.SQLOutput;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-09-24
 * Time: 22:31
 */
public class MyArrayList<E> {
    private Object[] elementData;
    private int usedSize;
    private static  int DEFAULT_CAPACITY =10;
    public static final Object [] EMPTY_ELEMENTDATA = {};
    public static final Object [] DEFAULTCAPACITY_EMPTY_ELEMENTDATA ={};

    //无参构造
    public MyArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }


    /**
     * 初始化指定list 大小为initialCapacity
     * @param initialCapacity
     */
    public MyArrayList(int initialCapacity){
        if(initialCapacity>0){
            this.elementData=new Object[initialCapacity];
        }else if(initialCapacity==0){
            this.elementData=EMPTY_ELEMENTDATA;
        }else {
            throw new IllegalArgumentException("数组大不能为负数");
        }
    }


    /**
     * 尾插
     * @param e
     * @return
     */
    public boolean add(E e){
        ensureCapacityInternal(usedSize+1);
        elementData[usedSize++]=e;
        return true;
    }


    /**
     * 检查下标的合法性
     * @param index
     */
    private void rangeCheckForAdd(int index){
        if(index<0||index>elementData.length){
            throw new IndexOutOfBoundsException("下标不在正确范围内");
        }
    }

    private void ensureCapacityInternal(int minCapacity){
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    /**
     * 确定具体的数组变成多大
     * @param minCapacity
     */

    private void ensureExplicitCapacity(int minCapacity){
        if(minCapacity-elementData.length>0){
            grow(minCapacity);
        }
    }

    /**
     * 扩容
     * @param minCapacity
     */
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + oldCapacity >> 1;
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            newCapacity = hugeCapacity(minCapacity);
        }
    }

    /**
     * 能给的最大数组大小
     * @param minCapacity
     * @return
     */
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }


    private static final int MAX_ARRAY_SIZE=Integer.MAX_VALUE-8;
    /**
     * 计算数组大小
     */
    private static int calculateCapacity(Object [] elementData,int minCapacity){
        if(elementData==DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
            return Math.max(DEFAULT_CAPACITY,minCapacity);
        }
        return minCapacity;
    }
}
